package com.mfp.java.testYou.ui.mvc;

import java.util.LinkedList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.mfp.java.testYou.core.servlets.ManageQuestionServlet;
import com.mfp.java.testYou.db.model.Answer;
import com.mfp.java.testYou.db.model.Question;
import com.mfp.java.testYou.model.UiSelectPair;

public class QuestionPage extends AbstractMVC {

	private static final Logger log = Logger.getLogger(QuestionPage.class);

	public static final String URL = "/testYou/pages/question.jsp";

	public static final String ATTR_EDIT_QUESTION = "editableQuestion";

	private Question question;

	public QuestionPage(HttpServletRequest request, HttpServletResponse response) {
		super(request, response);
		init();
	}

	private void init() {
		try {
			Object o = getRequest().getAttribute(ATTR_EDIT_QUESTION);
			if (o == null) {
				log.debug("No question found in request. Page is new Question Page");
				question = null;
				return;
			} else {
				log.debug("Question data found. Page is edit Question Page");
			}
			question = (Question) o;
		} catch (ClassCastException e) {
			log.error("Could not cast question class. Make sure to add question class as request attribute");
		}
	}

	public boolean isEdit() {
		return question != null;
	}

	public String getOperationName() {
		return isEdit() ? ManageQuestionServlet.OPERATION_CHANGE : ManageQuestionServlet.OPERATION_ADD;
	}

	public String getQuestionText() {
		if (!isEdit()) {
			return "";
		} else {
			return question.getText();
		}
	}

	public String getQuestionTextForEdit() {
		String q = getQuestionText();

		q = q.replaceAll("\n", "\\n");
		q = q.replaceAll("\r", "\\r");
		return q;
	}

	public String getHint() {
		return isEdit() ? question.getHint() : "";
	}

	public List<UiSelectPair> getAnswers() {
		List<UiSelectPair> list = new LinkedList<UiSelectPair>();
		for (Answer a : question.getAnswers()) {
			list.add(new UiSelectPair(a.getText(), "" + a.isCorect()));
		}
		return list;
	}

	public Integer getId() {
		return isEdit() ? question.getId() : 0;
	}
}
